express = require('express')
http = require('http')
path = require('path')
fs = require 'fs'
config = require './config'
db = require './utils/connect'

app = new express()
app.set('port', process.argv[2] || 80)
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.favicon())
app.use(express.logger('dev'))
app.use(express.bodyParser())
app.use(express.methodOverride())
app.use(app.router)
app.use(express.static(path.join(__dirname, 'public')))

app.qiniu = config.qiniu

if ('development' == app.get('env')) 
  app.use(express.errorHandler())

router = (app)->
	configRoute = (app,route,base)->
		for path, func of route
			console.log "#{path.split(' ')[0]} #{base+path.split(' ')[1]}"
			app[path.split(' ')[0]] path.split(' ')[1], func
	files = fs.readdirSync path.join __dirname , '/routes'
	routes = (i.split('.')[0] for i in files when /[js|coffee]/.test path.extname)
	routes.forEach (route)->
		configRoute app,require('./routes/'+route), route

router app
app.locals.db = db
process.on 'uncaughtException',(err)->
	console.log err
http.createServer(app).listen app.get('port'), ()->
  console.log('Express server listening on port ' + app.get('port'))
